package com.sedshop.shop;/**
 * Created by Administrator on 2016/4/22.
 */

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.bumptech.glide.DrawableRequestBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sedshop.shop.adapter.DividerGridItemDecoration;
import com.sedshop.shop.adapter.MyRecyclerAdapter;
import com.sedshop.shop.entity.FirstEventBus;
import com.sedshop.shop.entity.WeatherTest;
import com.sedshop.shop.interfaces.APIServiceTest;
import com.sedshop.shop.library.constant.AppConfig;
import com.sedshop.shop.library.fresco.FrescoUtils;
import com.sedshop.shop.library.umeng.share.Share;
import com.sedshop.shop.library.volley.LogUtils;
import com.sedshop.shop.library.volley.MyVolleyRequest;
import com.sedshop.shop.library.volley.UserException;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者：Administrator on 2016/4/22 09:35
 * 邮箱：314960314@qq.com
 */
public class TestActivity extends BaseActivity{

    private static String TAG = TestActivity.class.getSimpleName();

    @Bind(R.id.test_butterknife_btn) Button button;

    private Context mContext;

//    private String imageUrl = "http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg";

    private String imageUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";

    private String gifUrl = "http://jcodecraeer.com/uploads/allimg/150327/163Aa632-0.gif";

    @SuppressLint("NewApi") @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //测试Fresco
//        testFresco();
        //测试retrofit + okhttp
//        testWeather();
        //测试测试retrofit  +  rxjava + okhttp
//        testWeatherData();

        //测试RecyclerView
//        testRecylerView();

        //测试友盟统计
//        testAnalytics();

        //测试热修复
//        testHotFix();

        //测试友盟分享
//        testShare();

        //测试EventBus
//        testEventBus();

        //测试ButterKnife
//        testButterKnife();

        //测试imageLoader
//        testImageLoader();

        //测试volleyGet
//        testVolleyGet();

        //测试volleyPost,参数未配置,无返回数据
//        testVolleyPost();

        //测试Xutils加载图片
//        testXutilsBitmap();

        //测试Xutils网络请求
//        testXutilsGet();

        //测试Xutils网络请求,参数未配置,无返回数据
//        testXutilsPost();

        //测试Picasso
//        testPicasso();

        //测试glide
//        testGlide();

    }

    private void testGlide() {
        setContentView(R.layout.test_glide);
        ImageView mImageView = (ImageView)findViewById(R.id.imageView);
        Glide.with(this)
                .load(imageUrl)
                .crossFade()
                .into(mImageView);
    }

    private void testPicasso() {
        setContentView(R.layout.test_picasso);
        ImageView mImageView = (ImageView)findViewById(R.id.imageView);
        Picasso.with(this)
                .load(imageUrl)
                .noFade()
                .into(mImageView);
    }


    private void testXutilsPost() {
        setContentView(R.layout.test_xutils);
        final TextView testTextView = (TextView)findViewById(R.id.textView);

        RequestParams params = new RequestParams();
        params.addHeader("name", "value");
        params.addQueryStringParameter("name", "value");
        // 只包含字符串参数时默认使用BodyParamsEntity，
        // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
        params.addBodyParameter("name", "value");
        // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
        // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
        // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
        // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
        // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
        String path = "";
        params.addBodyParameter("file", new File(path));

        String url = "";

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        testTextView.setText("conn...");
                    }
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            testTextView.setText("upload: " + current + "/" + total);
                        } else {
                            testTextView.setText("reply: " + current + "/" + total);
                        }
                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        testTextView.setText("reply: " + responseInfo.result);
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        testTextView.setText(error.getExceptionCode() + ":" + msg);
                    }
                });
    }

    private void testXutilsGet() {
        setContentView(R.layout.test_xutils);
        final TextView tv = (TextView)findViewById(R.id.textView);

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET,
                "http://www.lidroid.com",
                new RequestCallBack<String>(){
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        tv.setText(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        tv.setText(responseInfo.result);
                    }
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });

    }

    private void testXutilsBitmap() {
        setContentView(R.layout.test_xutils);
        mContext = this;
        BitmapUtils bitmapUtils = new BitmapUtils(mContext);
        bitmapUtils.configDefaultLoadFailedImage(R.drawable.umeng_launcher);
        ImageView mImageView = (ImageView)findViewById(R.id.imageView);
        bitmapUtils.display(mImageView,imageUrl);
    }

    private void testVolleyPost() {
        mContext = this;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name1","value1");
            jsonObject.put("name2", "value2");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String url = "";

        MyVolleyRequest myVolleyRequest = new MyVolleyRequest(mContext);
        myVolleyRequest.sendRequest(com.android.myvolley.Request.Method.POST, url, jsonObject,
                new MyVolleyRequest.OnResponseListener() {
                    @Override
                    public boolean onResponse(JSONObject response) {
                        int code = response.optInt("code", 0);
                        Gson gson = new Gson();
                        if (code == 0) {
                            LogUtils.d(TAG, "response ============ " + response);
                        } else {
                            UserException userException = gson.fromJson(response.toString(), UserException.class);
                            Toast.makeText(mContext, userException.getText() + "", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                        LogUtils.d(TAG, "myVolleyRequest.sendRequest response = " + response);

                        return false;
                    }
                },
                new MyVolleyRequest.OnErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        UserException userException = new UserException();
                    }
                });
    }

    private void testVolleyGet() {
        setContentView(R.layout.test_volleys);
        mContext = this;
        String url = AppConfig.GROUPS_ALL_URL;
        final Gson gson = new Gson();

        MyVolleyRequest myVolleyRequest = new MyVolleyRequest(mContext);
        myVolleyRequest.sendRequest(com.android.myvolley.Request.Method.GET, url, null,
                new MyVolleyRequest.OnResponseListener() {
                    @Override
                    public boolean onResponse(JSONObject response) {
                        int code = response.optInt("code", 0);
                        if (code == 0) {
                            Log.d(TAG, "testVolley" + " " + response);
                            TextView tv = (TextView)findViewById(R.id.textView);
                            tv.setText(response.toString());
                        } else {
                            UserException userException = gson.fromJson(response.toString(), UserException.class);
                            LogUtils.d(TAG, "HttpException = " + userException.toString());
                        }
                        return false;
                    }
                },
                new MyVolleyRequest.OnErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        LogUtils.d(TAG, "HttpException = " + error);
                    }
                });
    }

    private void testImageLoader() {
        setContentView(R.layout.test_imageloader);
        ImageLoader mImageLoader = ImageLoader.getInstance();
        DisplayImageOptions mOptions;
        mOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.umeng_launcher)
                .showImageForEmptyUri(R.drawable.umeng_launcher)
                .showImageOnFail(R.drawable.umeng_launcher)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        ImageView mImageView = (ImageView)findViewById(R.id.imageView);
        mImageLoader.displayImage(imageUrl, mImageView, mOptions, null, null);
    }

    private void testButterKnife() {
        setContentView(R.layout.test_butterknife);
        ButterKnife.bind(TestActivity.this);
        button.setText("测试ButterKnife");
    }

    @OnClick(R.id.test_toast)
    public void butterKnifeToast(Button button) {
        button.setText("测试成功");
    }

    public void testEventBus(){
        EventBus.getDefault().register(this);
        setContentView(R.layout.test_share);
        Button shareBtn = (Button)findViewById(R.id.share_button);
        shareBtn.setText("测试跳转");
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), TestEventBusActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(FirstEventBus event) {
        String msg = "onEventMainThread收到了消息：" + event.getMsg();
        Log.d("harvic", msg);
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    private void testShare(){
        setContentView(R.layout.test_share);
        Button shareBtn = (Button)findViewById(R.id.share_button);
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Share share = new Share();
                share.share(TestActivity.this,"测试内容","http://www.baidu.com","测试标题","http://img05.tooopen.com/images/20140604/sy_62331342149.jpg");
            }
        });
    }

    private  void  testHotFix(){
    }



    private void testRecylerView() {
        setContentView(R.layout.test_recycler);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        List<String> mDatas  = new ArrayList<String>();
        for (int i=0; i < 40; i++) {
            mDatas.add("item"+i);
        }
        MyRecyclerAdapter recycleAdapter = new MyRecyclerAdapter(TestActivity.this, mDatas);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
//		layoutManager.setOrientation(OrientationHelper.HORIZONTAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
        recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recycleAdapter.setOnItemClickListener(new MyRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onLongClick(int position) {
                Toast.makeText(TestActivity.this,"onLongClick事件       您点击了第："+position+"个Item",Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onClick(int position) {
                Toast.makeText(TestActivity.this,"onClick事件       您点击了第："+position+"个Item",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        Context context = this;
//        getDeviceInfo(context);

    }
    @Override
    public void onPause() {
        super.onPause();
    }

    @SuppressLint("NewApi")
    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }

    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            Log.d(TAG, "device_id=  " + device_id);
            Log.d(TAG,"device_id =  " + mac);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    private void testAnalytics() {
        setContentView(R.layout.test_analytics);

        MobclickAgent.setDebugMode(true);
        MobclickAgent.openActivityDurationTrack(false);

        TextView textView1 = (TextView)findViewById(R.id.test_button_1);
        TextView textView2 = (TextView)findViewById(R.id.test_button_2);
        TextView textView3 = (TextView)findViewById(R.id.test_button_3);
        final Context context = this;
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //统计发生次数
                MobclickAgent.onEvent(context, "11");
                Toast.makeText(context,"11",Toast.LENGTH_SHORT).show();
            }
        });

        textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //统计点击行为各属性被触发的次数
                HashMap<String,String> map = new HashMap<String,String>();
                map.put("type","book");
                map.put("quantity","3");
                MobclickAgent.onEvent(context, "purchase", map);
                Toast.makeText(context, "purchase", Toast.LENGTH_SHORT).show();
            }
        });


        textView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //统计点击行为各属性被触发的次数
                //统计数值型变量的值的分布
                int duration = 12000; //开发者需要自己计算音乐播放时长
                Map<String, String> map_value = new HashMap<String, String>();
                map_value.put("type" , "popular" );
                map_value.put("artist" , "JJLin" );
                MobclickAgent.onEventValue(context, "music", map_value, duration);
                Toast.makeText(context, "music", Toast.LENGTH_SHORT).show();
            }
        });

    }


    public void testFresco(){
        Fresco.initialize(this);
        setContentView(R.layout.activity_main);
        FrescoUtils.displayImage(TestActivity.this, R.id.simpleDraweeView, imageUrl);
    }


    private void testWeather(){
        String apiKey = "e78cbbbc6753bc6a9b80383881663892";
        String baseUrl = "http://apis.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        APIServiceTest service = retrofit.create(APIServiceTest.class);

        Call<WeatherTest> infoCall = service.getWeather(apiKey, "杭州");
        infoCall.enqueue(new Callback<WeatherTest>() {
            @Override
            public void onResponse(Response<WeatherTest> response, Retrofit retrofit) {
                WeatherTest weather = response.body();
                if (response.isSuccess()) {
                    Log.d(TAG, "testWeatherData" + weather.getRetData().get(0).getName_cn());
                    Log.d(TAG, "testWeatherData" + weather.getRetData().get(0).getName_en());
                    Log.d(TAG, "testWeatherData" + weather.getRetData().get(0).getProvince_cn());
                }
            }
            @Override
            public void onFailure(Throwable t) {
            }
        });
    }

    private void testWeatherData(){
        String apiKey = "e78cbbbc6753bc6a9b80383881663892";
        String baseUrl = "http://apis.baidu.com/";

        OkHttpClient okHttpClient = new OkHttpClient();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        APIServiceTest service = retrofit.create(APIServiceTest.class);

        Observable<WeatherTest> observable = service.getWeatherData(apiKey, "杭州");
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WeatherTest>() {
                    @Override
                    public void onCompleted() {
                        Log.d(TAG, "testWeather onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "testWeather onError" + e);
                    }
                    @Override
                    public void onNext(WeatherTest weather) {
                        Log.d(TAG, "testWeather onNext" + weather.getRetData().toString());
                    }
                });
    }
}
